package io.renren.modules.generator.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.modules.generator.entity.GeneratorDepartmentEntity;
import io.renren.modules.generator.entity.GeneratorGroupsEntity;
import io.renren.modules.generator.entity.vo.UserAllInfoVo;
import io.renren.modules.generator.service.GeneratorDepartmentService;
import io.renren.modules.generator.service.GeneratorGroupsService;
import io.renren.modules.generator.service.GeneratorRolesService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.generator.entity.EmployeeInfoEntity;
import io.renren.modules.generator.service.EmployeeInfoService;
import io.renren.common.utils.R;


/**
 *
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-11-01 10:28:14
 */
@RestController
@RequestMapping("/generator/employeeinfo")
public class EmployeeInfoController extends AbstractController {
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService  sysRoleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private GeneratorRolesService generatorRolesService;
    @Autowired
    private GeneratorDepartmentService generatorDepartmentService;
    @Autowired
    private GeneratorGroupsService generatorGroupsService;

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:employeeinfo:list")
    public R list(@RequestBody(required = false) Map<String, Object> params){
        if (MapUtil.isEmpty(params)){
            params =  new HashMap<>();


        }
        System.out.println("测试");
        System.out.println(params);
           SysUserEntity currentUser = getUser();
          //  employeeInfoService.selectEmployeeUser(user);
        SysRoleEntity roleEntity = checkUserIsLive(currentUser);
        String roleName =roleEntity.getRoleName();
        IPage<EmployeeInfoEntity> employeeInfoEntityIPage =    employeeInfoService.getQueryPage(roleName,params,currentUser);
      return  R.ok().put("page",employeeInfoEntityIPage);
      /*  PageUtils page = employeeInfoService.queryPage(params,user);*/
    //    return R.ok().put("page", employeeInfoEntityIPage);

    }
     //验证用户是否具有一个角色， 不存在即报错  排除超级管理员
    private SysRoleEntity checkUserIsLive(SysUserEntity currentUser) {
        if(getUserId() != Constant.SUPER_ADMIN){
            Long  roleId = sysUserRoleService.queryRoleId(currentUser.getUserId());
            if (roleId==null){
                throw  new RRException("用户不存在角色",400);
            }
            SysRoleEntity role = sysRoleService.getById(roleId);
            if (role==null){
                throw  new RRException("用户不存在角色",400);
            }
            return  role;
        }
       //为超级管理员的情况时
        SysRoleEntity role = new SysRoleEntity();
        role.setRoleId(0L);
        role.setRoleName("超级权限管理员");
        return   role;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:employeeinfo:info")
    public R info(@PathVariable("id") Long id){

        SysUserEntity currentUser = getUser();
        SysRoleEntity roleEntity =  checkUserIsLive(currentUser);
        String roleName = roleEntity.getRoleName();
        EmployeeInfoEntity employeeInfo =    employeeInfoService.getInfo(roleName,currentUser,id);
     //   EmployeeInfoEntity employeeInfo2 = employeeInfoService.getById(id);

        return R.ok().put("employeeInfo", employeeInfo);
    }
    /**
     * 保存
     */
    @SysLog("生成员工，顺便添加用户")
    @RequestMapping("/save")
    @RequiresPermissions("generator:employeeinfo:save")
    public R save(@RequestBody EmployeeInfoEntity employeeInfo){
        System.out.println();
        System.out.println(employeeInfo);
        //先要判断他的权限;
        SysUserEntity currentUser = getUser();
        SysRoleEntity roleEntity =  checkUserIsLive(currentUser);
        String roleName = roleEntity.getRoleName();
        employeeInfoService.saveEmployeeInfo(roleName,currentUser,employeeInfo);
       // employeeInfoService.save(employeeInfo);
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改员工信息，顺便修改用户信息")
    @RequestMapping("/update")
    @RequiresPermissions("generator:employeeinfo:update")
    public R update(@RequestBody EmployeeInfoEntity employeeInfo){
      //  employeeInfoService.updateById()
        //先要判断他的权限;
        SysUserEntity currentUser = getUser();
        SysRoleEntity roleEntity =  checkUserIsLive(currentUser);
		//employeeInfoService.updateById(employeeInfo);
        String roleName = roleEntity.getRoleName();
		employeeInfoService.updateEmployeeInfo(roleName,currentUser,employeeInfo);

        return R.ok();
    }
    /**
     * 重置密码
     */
    @SysLog("重置密码")
    @RequestMapping("/reset/{id}")
    @RequiresPermissions("generator:employeeinfo:update")
    public R reset(@PathVariable Long id){
        System.out.println(id);
        if (id==null){
            throw  new RRException("ID 不存在",407);
        }
        //  employeeInfoService.updateById()
         String  password     =  employeeInfoService.reset(id);

        return R.ok().put("password",password);
    }


    @RequestMapping("/getAllDictionary")
  //  @RequiresPermissions("generator:generatordepartment:list")
    public R getAllDictionary(){
        System.out.println("是否能执行");
        List<GeneratorDepartmentEntity> department = generatorDepartmentService.getBaseMapper().selectList(null);
        List<GeneratorGroupsEntity> groups = generatorGroupsService.getBaseMapper().selectList(null);
        List<SysRoleEntity> roles = sysRoleService.getBaseMapper().selectList(null);
        HashMap<String,List> map = new HashMap<>();
        map.put("department",department);
        map.put("groups",groups);
        map.put("roles",roles);
        System.out.println(department);
        System.out.println(groups);
        System.out.println(roles);
        return R.ok().put("page", map);
    }
    @RequestMapping("/isChangePassword")
    //  @RequiresPermissions("generator:generatordepartment:list")
    public R isChangePassword(){
        System.out.println("当前的用户id");
        //需要修改密码时true ，不需要修改密码是false
        SysUserEntity currentUser = getUser();
    /*    String password = getUser().getPassword();*/
        //获取到当前的用户id   ，  通过这个id去判断是否改过密码 ；
      boolean    flag =     employeeInfoService.isChangePassword(currentUser);

        return R.ok().put("flag", flag);
    }


    @RequestMapping("/getUserInfo")
   //TODO 写的位置不太正确 ，之后可以修改位置
    public R getUserInfo(){
        SysUserEntity currentUser = getUser();
        if (currentUser.getUserId()==Constant.SUPER_ADMIN){//kankan
        }
        Long roleId = sysUserRoleService.queryRoleId(currentUser.getUserId());
        SysRoleEntity roleEntity = sysRoleService.getById(roleId);
        //返回用户信息和他的员工信息和他的权限 ，
        EmployeeInfoEntity   employeeInfoEntity         =    employeeInfoService.queryUserId(currentUser.getUserId());
            employeeInfoEntity.setRoles(roleEntity.getRoleName());
            employeeInfoEntity.setUsername(currentUser.getUsername());
        UserAllInfoVo userAllInfoVo = new UserAllInfoVo();
        BeanUtils.copyProperties(employeeInfoEntity, userAllInfoVo);
        String department = userAllInfoVo.getDepartment();
       if (StringUtils.isBlank(department)){
           userAllInfoVo.setDepartmentName(null);
       }else {
           QueryWrapper<GeneratorDepartmentEntity> gd = new QueryWrapper<>();
           gd.eq("department_int",department);
           userAllInfoVo.setDepartmentName( generatorDepartmentService.getOne(gd).getDepartmentName());
       }


        return  R.ok().put("user", userAllInfoVo);
    }



        /**
         * 删除 没有这个功能
         */
   /* @RequestMapping("/delete")
    @RequiresPermissions("generator:employeeinfo:delete")
    public R delete(@RequestBody Integer[] ids){
		employeeInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }*/


}
